<?php

namespace app\admin\controller\open;

use app\admin\service\auth\AdminService;
use app\model\auth\Admin;
use app\service\Captcha\AjCaptchaService;
use think\Request;

class LoginController
{
    public function login (Request $request, AdminService $adminService) {
        if(!$request->isPost()){
            return;
        }
        $data = $request->only(['username', 'password', 'captcha'], 'post');

        // 验证验证码
//        if (!captcha_check($data['captcha']??'')){
//            return jsonError('验证码错误',1002);
//        }


        // 验证码验证
        // todo: 从系统配置中获取验证方式
//        try{
//            (new AjCaptchaService())->verification('blockPuzzle', $data['captcha']);
//        }catch(\Exception $e){
//            return jsonError($e->getMessage());
//        }

        // 获取用户信息
        $admin = Admin::where('username', $data['username'])->where('password', md5($data['password']))->find();
        if (!$admin){
            return jsonError("用户名或密码错误");
        }

        if ($admin->status != 1){
            return jsonError("该账户已被禁用，请联系管理员");
        }

        // 更新登录ip和登录时间
        $admin->login_time = time();
        $admin->login_ip = request()->ip();
        $admin->save();

        // 创建日志
//        AdminLog::record();

        // 生成token
        $token = uuid();

        // 保存token到缓存
        $adminService->setLoginToken($token, $admin->id);

        return jsonSuccess([
            'token' => $token,
        ]);
    }

    public function logout(AdminService $adminService): \think\response\Json
    {
        $adminService->logout();
        return jsonSuccess();
    }
}
